package com.stony.orc;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取token类
 */
public class AuthService extends HttpService implements API{
    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);

    // 官网获取的 API Key 更新为你注册的
    String clientId = "GZor4bTiaeTo9RM2mmvSMExE";
    // 官网获取的 Secret Key 更新为你注册的
    String clientSecret = "WjmDMQEf1EwNlTSDxYRE3mh9y3xuNKZc";
    Token curToken;
    final Store store;

    public AuthService() {
        store = Store.newStore();
    }

    /**
     * 获取权限token
     *
     * @return 返回示例：
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public Token getAuth() {
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     *
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public Token getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = TOKEN + "?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            return JsonUtils.str2Obj(result, Token.class);
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }
    public Token getCurToken() {
        if(curToken == null) {
            curToken = getAuth();
        }
        return curToken;
    }
    public String identifyImageByGeneral2(String imageFileName) throws IOException{
        File imageFile = new File(imageFileName);
        Token token = getCurToken();
        String buffer = null;
        if(imageFile.exists()) {
            String destFile = ImageUtils.compressPicForScale(imageFileName, (imageFileName + ".thumb.jpg"), 3500, 0.8);
            logger.info("Identify Compress Image[{}] By General begin.", destFile);
            imageFile = new File(destFile);
            String url = GENERAL_BASIC + "?access_token="+token.getAccessToken();

            String imageBase = ImageUtils.encodeImgageToBase64(imageFile);
            buffer = submit(url, "image", imageBase);
            logger.debug("request GENERAL_BASIC buffer : " + buffer);
        } else {
            logger.warn("This image file[{}] is not exists.", imageFileName);
        }
        return buffer;
    }
    public String identifyImageByGeneral(String imageFileName) throws IOException{
        File imageFile = new File(imageFileName);
        Token token = getCurToken();
        StringBuilder buffer = new StringBuilder(256);
        if(imageFile.exists()) {
            String destFile = ImageUtils.compressPicForScale(imageFileName, (imageFileName + ".thumb.jpg"), 3500, 0.8);
            logger.info("Identify Compress Image[{}] By General begin.", destFile);
            imageFile = new File(destFile);
            int timeOut = 12000;
            String url = GENERAL_BASIC + "?access_token="+token.getAccessToken();

            URL realUrl = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setReadTimeout(timeOut);
            connection.setConnectTimeout(timeOut);

            String imageBase = ImageUtils.encodeImgageToBase64(imageFile);
            OutputStream output = connection.getOutputStream();
            output.write(("image=" + URLEncoder.encode(imageBase,"UTF-8")).getBytes("UTF-8"));
            output.flush();
            connection.connect();
            BufferedReader reader;

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));
            }
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            logger.debug("request GENERAL_BASIC buffer : " + buffer);
            output.close();
            connection.disconnect();
        } else {
            logger.warn("This image file[{}] is not exists.", imageFileName);
        }
        return buffer.toString();
    }
    public void processTonicImage(String imageFileName) throws IOException {
        String buffer = identifyImageByGeneral2(imageFileName);
        if(JsonUtils.isNotEmpty(buffer)) {
            JSONObject obj = JSON.parseObject(buffer);

            int wordsNum = obj.getInteger("words_result_num");
            if(wordsNum >= 1) {
                KeyWords keyWords = new KeyWords();
                JSONArray words_result = obj.getJSONArray("words_result");
                for (Object oa : words_result){
                    if(oa instanceof JSONObject) {
                        keyWords.process(((JSONObject) oa).getString("words"));
                    }
                }
                VisitRecord record = JsonUtils.str2Obj(JsonUtils.obj2Str(keyWords.getKeyWords()), VisitRecord.class);
                record.setTonicList(keyWords.processTonic());
                long id = store.saveVisitRecord(record);
                logger.info("process image[{}] return id = {}.", imageFileName, id);
                store.releaseConnection();
            }
        } else {
            logger.warn("Identify Image[{}] By General is null.", imageFileName);
        }
    }

    public void setToken(Token token) {
        this.curToken = token;
    }
}